package com.example.demo.thread.race;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Request ID 生成器
 * 部分系统为了便于跟踪对其收到的http请求的处理，会为其收到的每个http请求分配一个唯一编号（Request ID）
 *
 * @author: htc
 * @date: Created in 13:59 2019/1/7.
 */
public final class RequestIDGenerator {
    /**
     * 保存该类的唯一实例
     */
    private final static RequestIDGenerator INSTANCE = new RequestIDGenerator();

    private final static short SEQ_UPPER_LIMIT = 999;

    private short sequence = -1;

    private RequestIDGenerator() {
    }

    /**
     * 生成循环递增序列号
     *
     * @return
     */
    public short nextSequence() {
        if (sequence >= SEQ_UPPER_LIMIT) {
            sequence = 0;
        } else {
            sequence++;
        }
        return sequence;
    }

    /**
     * 生成一个新的request ID
     * @return
     */
    public String nextID() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        DecimalFormat df = new DecimalFormat("000");

        //生成请求序列号
        short sequence = nextSequence();
        return "0049" + timestamp + df.format(sequence);
    }

    /**
     * 返回该类的唯一实例
     * @return
     */
    public static RequestIDGenerator getInstance(){
        return INSTANCE;
    }
}
